package xr.ip.util;

import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;

/**
 * <p>
 * IP地址工具类
 * </p>
 *
 * @author Arnold Yang
 * @since 2018-04-02
 */
public class IpUtil {

  /**
   * 根据IP查询所属区域
   *
   * @param ip
   * @return 国家|区域|省份|城市|运营商
   */
  public static String geoLocation(String ip){
    try {
      DataBlock dataBlock = DirectSearcher.INSTANCE.getInstance().memorySearch(ip);
      return dataBlock.getRegion();
    }catch (Exception e){
//      e.printStackTrace();
    }

    return "";
  }

  private static enum DirectSearcher{
    INSTANCE("ip2region.db");

    private DbSearcher singleton;
    private String dbFile;

    private DirectSearcher(String dbFile) {
      this.dbFile = dbFile;
      try {
        // this.getClass().getClassLoader().getResource(dbFile).toString()
        singleton = new DbSearcher(new DbConfig(), this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath() + dbFile);
      }catch (Exception e){
//        e.printStackTrace();
      }
    }

    public DbSearcher getInstance(){
      return singleton;
    }

  }

//  private static enum DirectExecutor implements Executor {
//    INSTANCE;
//
//    private DirectExecutor() {
//    }
//
//    public void execute(Runnable command) {
//      command.run();
//    }
//
//    public String toString() {
//      return "MoreExecutors.directExecutor()";
//    }
//  }
}
